//
//  ViewController.m
//  One Construction
//
//  Created by apple on 2019/9/3.
//  Copyright © 2019 apple. All rights reserved.
//

#import "ViewController.h"
#import "registeredViewController.h"
#import "tabViewController.h"
#import "naviViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <sys/utsname.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property(nonatomic,strong)myButton *leftBackBtn;
@property(nonatomic,strong)myLable *loginLable;
@property(nonatomic,strong)UITextField *phoneTextField;
@property(nonatomic,strong)UITextField *passwordTextField;
@property(nonatomic,strong)myButton *loginBtn;
@property(nonatomic,strong)myButton *registeredBtn;
@property (nonatomic ,retain) CLLocationManager *locationManager;
@property(nonatomic,strong)NSString *lat;
@property(nonatomic,strong)NSString *lon;



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"登录";
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    [self locationStatt];
    [self creatUI];
    
}
- (void)creatUI{
    self.leftBackBtn = [[myButton alloc] initWithFrame:CGRectMake(16, AppNavitionHright/2, 43, 24)];
    [self.leftBackBtn setMyButtonIcon:nil TitileText:@"返回" TextFont:16 TitleColor:[UIColor colorWithRed:31/255.0 green:78/255.0 blue:196/255.0 alpha:1.0] BackColoc:[UIColor whiteColor]];
    //[self.view addSubview:self.leftBackBtn];
    //[self.leftBackBtn addTarget:self action:@selector(clickLeftBackBtn)forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.loginLable];
    
    //手机号的view
    UIView *phoneView = [[UIView alloc]initWithFrame:CGRectMake(28, self.loginLable.frame.origin.y+self.loginLable.frame.size.height+80, ScreenWidth-56, 70)];
    self.phoneTextField = [[UITextField alloc]init];
    
    [self creatView:phoneView lableText:@"手机号" textplac:@"请输入手机号" textField:self.phoneTextField];
    [self.view addSubview:phoneView];
    
    //手机号的view
    UIView *passwordView = [[UIView alloc]initWithFrame:CGRectMake(28, phoneView.frame.origin.y+phoneView.frame.size.height+30, ScreenWidth-56, 70)];
    self.passwordTextField = [[UITextField alloc]init];
    
    [self creatView:passwordView lableText:@"密码" textplac:@"请输入密码" textField:self.passwordTextField];
    [self.view addSubview:passwordView];
    
    //添加注册按钮
    [self.view addSubview:self.registeredBtn];
    [self.registeredBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-28);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(25);
        make.top.mas_equalTo(passwordView.mas_bottom).mas_offset(20);
    }];
    [self.registeredBtn addTarget:self action:@selector(clickRegistedBtn) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:self.loginBtn];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-28);
        make.left.mas_offset(28);
        make.height.mas_equalTo(50);
        make.top.mas_equalTo(self.registeredBtn.mas_bottom).mas_offset(33);
    }];
    [self.loginBtn addTarget:self action:@selector(clickLoginBtn) forControlEvents:UIControlEventTouchUpInside];
    
    self.passwordTextField.secureTextEntry = YES;
    
    
    
}
- (NSString *)getIphoneType{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString*platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    if([platform isEqualToString:@"iPhone1,1"])
         return @"iPhone 2G";
    if([platform isEqualToString:@"iPhone1,2"])
        return @"iPhone 3G";
    if([platform isEqualToString:@"iPhone2,1"])
         return @"iPhone 3GS";
    if([platform isEqualToString:@"iPhone3,1"])
         return @"iPhone 4";
    if([platform isEqualToString:@"iPhone3,2"])
         return @"iPhone 4";
    if([platform isEqualToString:@"iPhone3,3"])
         return @"iPhone 4";
    if([platform isEqualToString:@"iPhone4,1"])
        return @"iPhone 4S";
    if([platform isEqualToString:@"iPhone5,1"])
             return @"iPhone 5";
    if([platform isEqualToString:@"iPhone5,2"])
                 return @"iPhone 5";
    if([platform isEqualToString:@"iPhone5,3"])
                    return @"iPhone 5c";
    if([platform isEqualToString:@"iPhone5,4"])
         return @"iPhone 5c";
    if([platform isEqualToString:@"iPhone6,1"])
            return @"iPhone 5s";
    if([platform isEqualToString:@"iPhone6,2"])
         return @"iPhone 5s";
    if([platform isEqualToString:@"iPhone7,1"])
         return @"iPhone 6 Plus";if([platform isEqualToString:@"iPhone7,2"])
             return @"iPhone 6";
    if([platform isEqualToString:@"iPhone8,1"])
         return @"iPhone 6s";
    if([platform isEqualToString:@"iPhone8,2"])
        return @"iPhone 6s Plus";if([platform isEqualToString:@"iPhone8,4"])
             return @"iPhone SE";if([platform isEqualToString:@"iPhone9,1"])
                 return @"iPhone 7";
    if([platform isEqualToString:@"iPhone9,2"])
         return @"iPhone 7 Plus";if([platform isEqualToString:@"iPhone10,1"])
            return @"iPhone 8";
    if([platform isEqualToString:@"iPhone10,4"])
        return @"iPhone 8";
    if([platform isEqualToString:@"iPhone10,2"])
        return @"iPhone 8 Plus";
    if([platform isEqualToString:@"iPhone10,5"])
        return @"iPhone 8 Plus";
    if([platform isEqualToString:@"iPhone10,3"])
            return @"iPhone X";
    if([platform isEqualToString:@"iPhone10,6"])
                return @"iPhone X";
    if([platform isEqualToString:@"iPhone11,8"])
        return @"iPhone XR";
    if([platform isEqualToString:@"iPhone11,2"])
        return @"iPhone XS";
    if([platform isEqualToString:@"iPhone11,4"])
        return @"iPhone XS Max";
    if([platform isEqualToString:@"iPhone11,6"])
        return @"iPhone XS Max";
    
    if([platform isEqualToString:@"iPod1,1"])
                     return @"iPod Touch 1G";
    if([platform isEqualToString:@"iPod2,1"])
        return @"iPod Touch 2G";
    if([platform isEqualToString:@"iPod3,1"])
            return @"iPod Touch 3G";
    if([platform isEqualToString:@"iPod4,1"])
         return @"iPod Touch 4G";
    if([platform isEqualToString:@"iPod5,1"])
            return @"iPod Touch 5G";
    if([platform isEqualToString:@"iPad1,1"])
                return @"iPad 1G";
    if([platform isEqualToString:@"iPad2,1"])
                     return @"iPad 2";
    if([platform isEqualToString:@"iPad2,2"])
                         return @"iPad 2";
    if([platform isEqualToString:@"iPad2,3"])
        return @"iPad 2";
    if([platform isEqualToString:@"iPad2,4"])
        return @"iPad 2";
    if([platform isEqualToString:@"iPad2,5"])
         return @"iPad Mini 1G";
    if([platform isEqualToString:@"iPad2,6"])
         return @"iPad Mini 1G";
    if([platform isEqualToString:@"iPad2,7"])
        return @"iPad Mini 1G";
    if([platform isEqualToString:@"iPad3,1"])
         return @"iPad 3";
    if([platform isEqualToString:@"iPad3,2"])
        return @"iPad 3";
    if([platform isEqualToString:@"iPad3,3"])  return @"iPad 3";
    if([platform isEqualToString:@"iPad3,4"])
         return @"iPad 4";
    if([platform isEqualToString:@"iPad3,5"])  return@"iPad 4";
    if([platform isEqualToString:@"iPad3,6"])  return @"iPad 4";
    if([platform isEqualToString:@"iPad4,1"])  return @"iPad Air";
    if([platform isEqualToString:@"iPad4,2"])  return @"iPad Air";
    if([platform isEqualToString:@"iPad4,3"])  return @"iPad Air";
    if([platform isEqualToString:@"iPad4,4"])  return @"iPad Mini 2G";
    if([platform isEqualToString:@"iPad4,5"])  return @"iPad Mini 2G";
    if([platform isEqualToString:@"iPad4,6"])  return @"iPad Mini 2G";
    if([platform isEqualToString:@"iPad4,7"])  return @"iPad Mini 3";
    if([platform isEqualToString:@"iPad4,8"])  return @"iPad Mini 3";
    if([platform isEqualToString:@"iPad4,9"])  return @"iPad Mini 3";
    if([platform isEqualToString:@"iPad5,1"])  return @"iPad Mini 4";
    if([platform isEqualToString:@"iPad5,2"])  return @"iPad Mini 4";
    if([platform isEqualToString:@"iPad5,3"])  return @"iPad Air 2";
    if([platform isEqualToString:@"iPad5,4"])  return @"iPad Air 2";
    if([platform isEqualToString:@"iPad6,3"])  return @"iPad Pro 9.7";
    if([platform isEqualToString:@"iPad6,4"])  return @"iPad Pro 9.7";
    if([platform isEqualToString:@"iPad6,7"])  return @"iPad Pro 12.9";
    if([platform isEqualToString:@"iPad6,8"])  return @"iPad Pro 12.9";
    if([platform isEqualToString:@"i386"])  return @"iPhone Simulator";
    if([platform isEqualToString:@"x86_64"])  return @"iPhone Simulator";
    return platform;
    
   
    
}


//点击返回按钮
- (void)clickLeftBackBtn{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
//点击登录按钮
- (void)clickLoginBtn{
    if (_phoneTextField.text.length == 0) {
        [ProgressHUD showText:@"请先输入手机号" icon:[UIImage imageNamed:@""] mode:MBProgressHUDModeText onView:self.view duration:1.0];
    }
    else{
        if(_phoneTextField.text.length<11||_phoneTextField.text.length>11) {
            
            [ProgressHUD showText:@"请输入正确的手机号格式" icon:[UIImage imageNamed:@""] mode:MBProgressHUDModeText onView:self.view duration:1.0];
            
            
            
        }
        else{
            if (self.passwordTextField.text.length == 0) {
                [ProgressHUD showText:@"请输入密码" icon:[UIImage imageNamed:@""] mode:MBProgressHUDModeText onView:self.view duration:1.0];
            }}}
    
    if(self.phoneTextField.text.length == 11 &&self.passwordTextField.text.length !=0 ){
        
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//        NSString *drivice_id  = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
         NSString *drivice_id  = [UUIDManager getDeviceID];
        NSString *version  = [infoDictionary objectForKey:@"CFBundleVersion"];
//        NSString *phone_lx  =[[UIDevice currentDevice] model] ;
         NSString *phone_lx  =[self getIphoneType];
        NSString *phone_version = [[UIDevice currentDevice] systemVersion];
        
        
        
        NSDictionary *dict = @{@"user_phone":_phoneTextField.text,
                               @"user_password":_passwordTextField.text,
                               @"drivice_id":drivice_id,
                               @"version":version,
                               @"phone_lx":phone_lx,
                               @"phone_version":phone_version,
                               @"lat":self.lat,
                               @"lon":self.lon,
                               };
        [CZNetWork post:@"https://i.zhongjianedu.com/ios.php/104/user/login2" params:dict success:^(id success) {
            NSString *isloginSTr = success[@"event"];
            if ([isloginSTr isEqualToString:@"100"]) {
                [ProgressHUD showText:@"登录中" icon:[UIImage imageNamed:@""] mode:MBProgressHUDModeIndeterminate onView:self.view duration:1.0];
                [User sharedUUser].user_phone = self.phoneTextField.text;
                [User sharedUUser].user_id = success[@"objList"][@"user_id"];
                
                [User sharedUUser].user_imageViewName = success[@"objList"][@"user_pic"];
                
                [User sharedUUser].user_name = success[@"objList"][@"user_phone"];
                if ([User sharedUUser].isLogin==YES) {
                    
                }
                tabViewController *tab = [[tabViewController alloc]init];
                [self presentViewController:tab animated:YES completion:^{
                    
                }];
                
                
            }
            if ([isloginSTr isEqualToString:@"101"]) {
                [ProgressHUD showText:@"请输入正确的数据" icon:[UIImage imageNamed:@""] mode:MBProgressHUDModeText onView:self.view duration:1.0];
            }
            if ([isloginSTr isEqualToString:@"102"]) {
                [ProgressHUD showText:@"无此用户，请查看号码是否正确或请先注册" icon:[UIImage imageNamed:@""] mode:MBProgressHUDModeText onView:self.view duration:1.0];
            }
            if ([isloginSTr isEqualToString:@"103"]) {
                [ProgressHUD showText:@"密码错误" icon:[UIImage imageNamed:@""] mode:MBProgressHUDModeText onView:self.view duration:1.0];
            }
            if ([isloginSTr isEqualToString:@"104"]) {
                [ProgressHUD showText:@"服务器繁忙" icon:[UIImage imageNamed:@""] mode:MBProgressHUDModeText onView:self.view duration:1.0];
            }
            
        } failure:^(NSError *error) {
            
            
        }];
        
    }
    
}
- (void)locationStatt{
    //判断定位操作是否被允许
    
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        //设置定位精度
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次（这里的设置为每隔百米)
        if ([[[UIDevice currentDevice] systemVersion]floatValue]>=8.0) {
            //使用应用程序期间允许访问位置数据
            [self.locationManager requestWhenInUseAuthorization];
        }
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        NSLog(@"%@",@"定位服务当前可能尚未打开，请设置打开！");
        
    }
}
#pragma mark - CoreLocation Delegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations

{
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [self.locationManager stopUpdatingLocation];
    // 保存 Device 的现语言 (英语 法语 ，，，)
    NSMutableArray *userDefaultLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    // 强制 成 简体中文
    [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"zh-hans",nil] forKey:@"AppleLanguages"];
    
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D ld = currentLocation.coordinate;
    
    
    
 double lati  =currentLocation.coordinate.latitude;
    double longi = currentLocation.coordinate.longitude;
    self.lat = [[NSNumber numberWithDouble:ld.latitude]stringValue];
    self.lon = [[NSNumber numberWithDouble: ld.longitude]stringValue];
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error){

        
        
        
        
        if (placemarks.count >0){
            
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            
            NSString *city=placemark.locality;
            NSString *cit = placemark.subLocality;
            NSString *na = placemark.name;
            
            NSString *string = [NSString stringWithFormat:@"%@%@",cit,na];
//            self.mapLableString  = string;
//            self.mapLable.text = self.mapLableString;
            // NSLog(@"在这里写的是区域和具体位置%@",self.mapLableString);
            
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            
        } else if (error ==nil && [placemarks count] == 0){
            
            NSLog(@"No results were returned.");
            //            self.Str = @"定位失败";
            //            [self.Button removeFromSuperview];
            //            self.Button = nil;
            //            self.Button.backgroundColor = [UIColor whiteColor];
            
            
        }else if (error !=nil){
            
            NSLog(@"An error occurred = %@", error);
            //            self.Str = @"定位失败";
            //            [self.Button removeFromSuperview];
            //            self.Button = nil;
            //            self.Button.backgroundColor = [UIColor whiteColor];
            
        }
        // 还原Device 的语言
        [[NSUserDefaults standardUserDefaults] setObject:userDefaultLanguages forKey:@"AppleLanguages"];
    }];
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    if (error.code ==kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
        NSLog(@"%@",error);
    }
    
}
//点击注册按钮
- (void)clickRegistedBtn{
    registeredViewController *reg = [[registeredViewController alloc]init];
    //    [self presentViewController:reg animated:YES completion:^{
    //
    //    }];
    //
    [self.navigationController pushViewController:reg animated:YES];
    
}
- (void)creatView:(UIView *)viewcc lableText:(NSString *)labletext textplac:(NSString *)plac textField:(UITextField *)textfield {
    viewcc.backgroundColor = [UIColor whiteColor];
    
    myLable *lable = [[myLable alloc]initWithFrame:CGRectMake(10, 0, 50, 28)];
    lable.text  = labletext;
    lable.textColor = [UIColor colorWithRed:160/255.0 green:160/255.0 blue:160/255.0 alpha:1.0];
    lable.font = [UIFont systemFontOfSize:16];
    [viewcc addSubview:lable];
    
    textfield.placeholder = plac;
    textfield.textColor = [UIColor blackColor];
    [viewcc addSubview:textfield];
    textfield.frame = CGRectMake(lable.frame.origin.x, lable.frame.origin.y+lable.frame.size.height+10, 170, 25);
    
    textfield.font = [UIFont systemFontOfSize:18];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, viewcc.frame.size.height-1, viewcc.frame.size.width, 0.5)];
    lineView.backgroundColor = [UIColor colorWithRed:160/255.0 green:160/255.0 blue:160/255.0 alpha:1.0];
    [viewcc addSubview:lineView];
}
- (myLable *)loginLable{
    if (!_loginLable) {
        _loginLable = [[myLable alloc]initWithFrame:CGRectMake(38, AppNavitionHright+44, 70, 42)];
        [_loginLable setLabletextColor:[UIColor blackColor] Text:@"登录" TextFont:30];
        
    }
    return _loginLable;
}
- (myButton *)registeredBtn{
    if (!_registeredBtn) {
        _registeredBtn = [[myButton alloc]init];
        [_registeredBtn setMyButtonIcon:[UIImage imageNamed:@""] TitileText:@"注册新用户" TextFont:18 TitleColor: [UIColor colorWithRed:31/255.0 green:78/255.0 blue:196/255.0 alpha:1.0] BackColoc:[UIColor whiteColor]];
    }
    return _registeredBtn;
}
- (myButton *)loginBtn{
    if (!_loginBtn) {
        _loginBtn = [[myButton alloc]init];
        [_loginBtn setMyButtonIcon:[UIImage imageNamed:@""] TitileText:@"登录" TextFont:18 TitleColor:[UIColor whiteColor] BackColoc:[UIColor colorWithRed:31/255.0 green:78/255.0 blue:196/255.0 alpha:1.0]];
        _loginBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        _loginBtn.layer.cornerRadius = 10;
        
        
    }
    return _loginBtn;
}

@end
